//算法代码在这


//填充
//根据对象{x, y}填充当前种子所在行
//返回由最左边，最右边，当前y组成的对象
function fillLine(obj) {
  let l = obj.x;
  let r = obj.x;
  let y = obj.y;
  point(l, y);
  while (!map[r + 1][y]) { point(++r, y); }
  while (!map[l - 1][y]) { point(--l, y); }
  return { l, r, y };
}

function fill() {
  ctx.fillStyle = BLUE;
  const stack = [{//定义一个栈
    x: seedx,
    y: seedy
  }];
  let res = null;
  let l = 0, r = 0, y = 0, up = 0, down = 0;
  let isRecordUp = false, isRecordDown = false;
  while (stack.length !== 0) {//主循环
    res = fillLine(stack.pop());
    l = res.l, r = res.r, y = res.y;
    isRecordDown = false;
    isRecordUp = false;
    for (let i = l; i <= r; i++) {//找上下种子并入栈
      if (!map[i][y + 1]) {//上一行的种子
        up = i;
        isRecordUp = true;
      } else {
        if (isRecordUp) {
          stack.push({
            x: up,
            y: y + 1
          });
          seeds.push({
            x: up,
            y: y + 1
          });
          isRecordUp = false;
        }
      }

      if (!map[i][y - 1]) {//下一行的种子
        down = i;
        isRecordDown = true;
      } else {
        if (isRecordDown) {
          stack.push({
            x: down,
            y: y - 1
          });
          seeds.push({
            x: down,
            y: y - 1
          });
          isRecordDown = false;
        }
      }
    }
    if (isRecordUp) {//处理上一行残留情况
      stack.push({
        x: up,
        y: y + 1
      });
      seeds.push({
        x: up,
        y: y + 1
      });
    }
    if (isRecordDown) {//处理下一行残留情况
      stack.push({
        x: down,
        y: y - 1
      });
      seeds.push({
        x: down,
        y: y - 1
      });
    }
  }
}



/**
 *     if(!map[l - 1][y + 1]){
      stack.push({x:l - 1, y:y + 1});
      seeds.push({x:l - 1, y:y + 1});
    }
    if(!map[r + 1][y + 1]){
      stack.push({x:r + 1, y:y + 1});
      seeds.push({x:r + 1, y:y + 1});
    }
    if(!map[l - 1][y - 1]){
      stack.push({x:l - 1, y:y - 1});
      seeds.push({x:l - 1, y:y - 1});
    }
    if(!map[l + 1][y - 1]){
      stack.push({x:l + 1, y:y - 1});
      seeds.push({x:l + 1, y:y - 1});
    }
 */